package com.xwy.interceptor;

import com.alibaba.fastjson.JSON;
import com.xwy.service.UserService;
import com.xwy.util.JwtAuthTokenUtil;
import com.xwy.util.TokenContext;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Resource
    JwtAuthTokenUtil jwtAuthTokenUtil;
    @Resource
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("JWTHeaderName");
        String uri = request.getRequestURI();
        System.out.println(token+"===================================="+uri);
        Map<String, Object> map = new HashMap<>();
        if (!StringUtils.isEmpty(token)) {
            boolean b = jwtAuthTokenUtil.verifierToken(token);
            if(b) {
                String uno = jwtAuthTokenUtil.getUsernameFromToken(token);
                boolean result = userService.findAuthByUserId(uno, uri);
                TokenContext.setUno(uno);
                if (!result) {
                    map.put("status", 1);
                    map.put("message", "403NoAuth");
                    response.getWriter().write(JSON.toJSONString(map));
                }
                return result;
            }else{
                map.put("status",1);
                map.put("message","tokenerr");
                response.getWriter().write(JSON.toJSONString(map));
            }
        }else {
            map.put("status",1);
            map.put("message","tokennull");
            response.getWriter().write(JSON.toJSONString(map));
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
